package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author:YZN
 * @date:2023/1/7
 * @description:
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public R shoppingList() {
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(null);

        return R.success(shoppingCarts);
    }

    @Override
    public R addCart(ShoppingCart shoppingCart) {
        if (null == shoppingCart) {
            return R.error("参数异常");
        }
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();

        ShoppingCart oldCart = null;
        //如果已添加该类型 则数量加1
        if (dishId != null) {
            oldCart = shoppingCartMapper.selectOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getDishId, dishId));
        } else {
            oldCart = shoppingCartMapper.selectOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getSetmealId, setmealId));
        }

        if (oldCart != null) {
            oldCart.setNumber(oldCart.getNumber() + 1);
            shoppingCartMapper.updateById(oldCart);
        } else {
            shoppingCart.setUserId(BaseContext.getCurrenId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCartMapper.insert(shoppingCart);
        }
        return R.success("加入购物车成功!");
    }


    @Override
    public R deleteCart() {
        shoppingCartMapper.delete(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, BaseContext.getCurrenId()));
        return R.success("清空购物车成功");
    }

    @Override
    public R subCart(ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        if (dishId != null) {
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
        } else {
            queryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        ShoppingCart cart = shoppingCartMapper.selectOne(queryWrapper);
        Integer number = cart.getNumber() - 1;
        if (number <= 0) {
            shoppingCartMapper.deleteById(cart.getId());
        }
        cart.setNumber(number);
        shoppingCartMapper.updateById(cart);

        return R.success("减少成功");
    }
}
